package com.lry.basic.algorithm.loadbanlance;


/**
 *  平滑加权轮询
 *  固定权重weight:A:1，B:2，C:3
 *  动态权重curWeight:A:0,B:0,C:0
 *  计算totalWeight6
 *  curWeight[i]+=weight[i]    (max curWeight)  返回ip   (max curWeight)-totalWeight
 *  curWeight：1，2，3                 3           C               1,2,-3
 *  curWeight:2,4,0                   4           B               2,-2,0
 *  curWeight:3,0,3                   3           A               -3,0,3
 *  curWeight:-2,2,6                  6           C               -2,2,0
 */
public class SmoothWeightRoundRobin {

    private static int[] curWeight = new int[WeightServer.servers.size()];

    public static Server getServer(){
        int totalWeight = 0;

        for(int i=0;i<curWeight.length;i++){
            Server server = WeightServer.servers.get(i);
            totalWeight += server.getWeight();
            curWeight[i]+= server.getWeight();
        }

        int maxWeightI = 0;
        int maxWeight = curWeight[0];
        for(int i=1;i<curWeight.length;i++){
            if(curWeight[i]>maxWeight){
                maxWeightI = i;
                maxWeight = curWeight[i];
            }
        }

        curWeight[maxWeightI]-=totalWeight;

        return WeightServer.servers.get(maxWeightI);

    }

    public static void main(String[] args) {
        for(int i=0;i<30;i++){
            Server server = getServer();
            server.setCallNum(server.getCallNum()+1);
            System.out.println(server);
        }
        System.out.println("-------------------------------------------------------");

        for(Server server:WeightServer.servers){
            System.out.println(server);
        }
    }

}
